package com.winit.openapi.wop.inbound.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.spi.context.CommandContext;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.ValidateUtil;
import com.winit.ups.spi.systemrule.CarrierService;
import com.winit.ups.spi.systemrule.UpsCarrierService;
import com.winit.ups.spi.systemrule.command.QueryUpsCarrierByTypeCommand;
import com.winit.ups.spi.systemrule.vo.UpsCarrierVo;

@Controller
@RequestMapping(value = "winit/ups/carrier")
public class WHInboundCarrierController extends BaseController {

    @Resource
    private CarrierService    upsCarrierService;

    @Resource
    private UpsCarrierService upsShipperService;

    @RequestMapping(value = "/getCarriers")
    public String getCarriers(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        JSONObject json = null;
        if (obj instanceof JSONObject) {
            json = (JSONObject) obj;
            // type不能为空
            ValidateUtil.validNotNull(json, "shipperType");
            ValidateUtil.validMaxLength(json, "shipperType", 50, true);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        QueryUpsCarrierByTypeCommand command = JSON.parseObject(requestMsg.getData().toString(),
            QueryUpsCarrierByTypeCommand.class);
        command.setCtx(CommandContext.getContext());
        List<UpsCarrierVo> vos = upsShipperService.getCarriersByType(command);
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        if (CollectionUtils.isNotEmpty(vos)) {
            for (UpsCarrierVo vo : vos) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("shipperCode", vo.getShipperCode());
                map.put("shipperName", vo.getShipperName());
                list.add(map);
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("carrierList", list);
        responseMsg.setData(map);

        return SUCCESS;
    }

}
